#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
图像处理与识别模块
"""

import base64
import os
import requests
import json
import logging
from pathlib import Path
import sys

# 添加项目根目录到路径
sys.path.append(str(Path(__file__).parent.parent))

from config import get_current_config


class ImageProcessor:
    """
    图像处理器类，负责处理和识别图像
    """
    def __init__(self):
        """
        初始化图像处理器
        """
        self.configured = False
        
        # 尝试获取配置
        try:
            from config import get_config_manager
            manager = get_config_manager()
            config = manager.get_current_config()
            
            # 检查API密钥是否有效
            provider, model = manager.get_current_provider_model()
            api_key = manager.get_api_key(provider)
            
            self.configured = bool(api_key and 'your-' not in str(api_key))
            
            if self.configured:
                logging.info(f"已配置 {provider} 提供商的 {model} 模型")
            else:
                logging.warning("未配置有效的API密钥，将使用示例数据")
                
        except Exception as e:
            logging.warning(f"获取模型配置失败: {e}，将使用示例数据")
            self.configured = False
    
    def process_image(self, image_path):
        """
        处理图片并识别图形元素
        
        Args:
            image_path (str): 图片文件路径
            
        Returns:
            dict: 包含识别到的图形元素信息
        """
        # 获取当前配置
        try:
            from config import get_config_manager
            manager = get_config_manager()
            provider, model = manager.get_current_provider_model()
            
            if not provider or not model:
                print("提示: 未配置提供商和模型，使用示例数据")
                return self._get_sample_data()
            
            # 获取完整的配置信息
            model_config = manager.get_model_config(provider, model)
            if not model_config:
                print("提示: 无法获取模型配置，使用示例数据")
                return self._get_sample_data()
            
            # 获取API密钥
            api_key = manager.get_api_key(provider)
            if not api_key or 'your-' in str(api_key):
                print(f"提示: 请配置 {provider} 提供商的API密钥，当前使用示例数据")
                return self._get_sample_data()
            
            # 设置配置信息
            self.api_key = api_key
            self.base_url = model_config['base_url']
            self.model = model
            self.headers = model_config.get('headers', {})
            self.provider = provider
            
            logging.info(f"已配置 {provider} - {model} 模型，准备使用实际API")
            
        except Exception as e:
            print(f"获取配置失败: {e}，使用示例数据")
            return self._get_sample_data()
            
        try:
            # 读取并编码图片
            with open(image_path, 'rb') as image_file:
                image_data = base64.b64encode(image_file.read()).decode('utf-8')
                
            # 构建请求头
            headers = {
                'Content-Type': 'application/json'
            }
            
            # 处理不同提供商的认证方式
            if 'azure' in self.provider.lower():
                # Azure OpenAI
                headers['api-key'] = self.api_key
            elif 'anthropic' in self.provider.lower():
                # Anthropic Claude
                headers['x-api-key'] = self.api_key
                headers['anthropic-version'] = '2023-06-01'
            else:
                # OpenAI兼容格式
                headers['Authorization'] = f'Bearer {self.api_key}'
            
            # 添加自定义头部
            custom_headers = self.headers
            headers.update(custom_headers)
            
            # 构建请求数据
            payload = {
                'model': self.model,
                'max_tokens': 1000,
                'messages': [
                    {
                        'role': 'user',
                        'content': [
                            {
                                'type': 'text',
                                'text': '分析这张图片中的几何图形，返回一个包含lines和circles的JSON对象。lines应该包含start和end坐标，circles应该包含center和radius。'
                            },
                            {
                                'type': 'image_url',
                                'image_url': {
                                    'url': f'data:image/jpeg;base64,{image_data}'
                                }
                            }
                        ]
                    }
                ]
            }
            
            # 发送请求
            timeout = 30
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers=headers,
                json=payload,
                timeout=timeout
            )
            
            if response.status_code == 200:
                result = response.json()
                
                # 处理不同提供商的响应格式
                if 'anthropic' in self.provider.lower():
                    # Claude响应格式
                    content = result['content'][0]['text']
                else:
                    # OpenAI兼容格式
                    content = result['choices'][0]['message']['content']
                
                # 解析返回的JSON
                try:
                    return json.loads(content)
                except json.JSONDecodeError:
                    print("警告: API返回格式不正确，使用示例数据")
                    return self._get_sample_data()
            else:
                print(f"API调用失败: {response.status_code} - {response.text}")
                return self._get_sample_data()
                
        except Exception as e:
            print(f"处理图片时出错: {e}")
            return self._get_sample_data()
    
    def _get_sample_data(self):
        """
        获取示例数据，用于API调用失败时的备用方案
        
        Returns:
            dict: 示例图形元素信息
        """
        return {
            "lines": [
                {"start": (0, 0), "end": (100, 100)},
                {"start": (100, 100), "end": (200, 50)}
            ],
            "circles": [
                {"center": (150, 150), "radius": 30}
            ]
        }

    def get_export_formats(self):
        """获取支持的导出格式"""
        try:
            from config import get_export_formats
            formats = get_export_formats()
            return [fmt for fmt, enabled in formats.items() if enabled]
        except ImportError:
            # 如果配置模块不可用，返回默认格式
            return ['dxf', 'svg', 'stl', 'obj', 'step', 'iges']